import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:pax_info_app/db/sql_provider.dart';
import 'package:pax_info_app/model/clock.dart';
import 'package:pax_info_app/utils/code_utils.dart';
import 'package:sqflite/sqflite.dart';

/**
 * 打卡记录表
 * Created by zongjian
 * Date: 2018-08-07
 */

class ClockDbProvider extends BaseDbProvider {
  final String name = 'Clock';

  final String columnId = "id";
  final String columnUserNo = "userNo";
  final String columnUserName = "userName";
  final String columnFAMType = "fAMType";
  final String columnFPMType= "fPMType";
  final String columnFAM = "fAM";
  final String columnFPM = "fPM";
  final String columnFDate = "fDate";
  final String columnIsHoliday = "isHoliday";
  final String columnLateDays = "lateDays";
  final String columnLeaveEarlyDays = "leaveEarlyDays";
  final String columnSalaryDays = "salaryDays";

  int? id;
  int? userNo;
  String? userName;
  String? fAMType;
  String? fPMType;
  String? fAM;
  String? fPM;
  String? fDate;
  int? isHoliday;
  int? lateDays;
  int? leaveEarlyDays;
  int? salaryDays;

  ClockDbProvider();

  Map<String, dynamic> toMap(Map data) {
    Map<String, dynamic> map = {
      columnId: data['ID'],
      columnUserNo: data['UserNo'],
      columnUserName: data['UserName'],
      columnFAMType: data['FAMType'],
      columnFPMType: data['FPMType'],
      columnFAM: data['FAM'],
      columnFPM: data['FPM'],
      columnFDate: data['FDate'],
      columnIsHoliday: data['IsHoliday'],
      columnLateDays: data['LateDays'],
      columnLeaveEarlyDays: data['LeaveEarlyDays'],
      columnSalaryDays: data['SalaryDays']};
    // if (data['id'] != null) {
    //   map[columnId] = data['id'];
    // }
    return map;
  }

  ClockDbProvider.fromMap(Map map) {
    id = map[columnId];
    userNo = map[columnUserNo];
    userName = map[columnUserName];
    fAM = map[columnFAM];
    fPM = map[columnFPM];
    fAMType = map[columnFAMType];
    fPMType = map[columnFPMType];
    fDate = map[columnFDate];
    isHoliday = map[columnIsHoliday];
    lateDays = map[columnLateDays];
    leaveEarlyDays = map[columnLeaveEarlyDays];
    salaryDays = map[columnSalaryDays];
  }

  @override
  tableSqlString() {
    return '''
        create table $name (
        $columnId integer integer primary key,
        $columnUserNo integer,
        $columnUserName text not null,
        $columnFAMType text,
        $columnFPMType text,
        $columnFAM text,
        $columnFPM text,
        $columnFDate text,
        $columnIsHoliday integer default 0,
        $columnLateDays integer default 0,
        $columnLeaveEarlyDays integer default 0,
        $columnSalaryDays integer default 0)
      ''';
  }

  @override
  tableName() {
    return name;
  }

  Future _getClockProvider(Database db, String id) async {
    List<Map<String, dynamic>> maps = await db.query(name,
        // columns: [columnId, columnUserName, columnData],
        where: "$columnId = ?",
        whereArgs: [id]);
    if (maps.length > 0) {
      ClockDbProvider provider = ClockDbProvider.fromMap(maps.first);
      return provider;
    }
    return null;
  }

  Future batchInsert(List<Map> datas) async {
    print('>>>>>> batchInsert: $datas');
    baseBatchInsert(name, datas, toMap);
  }

  ///插入到数据库
  Future insert(Map data) async {
    Database db = await getDataBase();
    var clockProvider = await _getClockProvider(db, data['ID']);
    if (clockProvider != null) {
      await db
          .delete(name, where: "$columnId = ?", whereArgs: [data['ID']]);
    }
    return await db.insert(name, toMap(data));
  }

  /// 获取数据
  Future<List<Clock>?> getData({String? fDate}) async {
    Database db = await getDataBase();
    List<Map<String, dynamic>> maps = [];
    if (fDate != null) {
      maps = await db.rawQuery(
          'SELECT * FROM $name WHERE $columnFDate LIKE "$fDate%"',
          null
      );
    } else {
      maps = await db.query(name);
    }
    if (maps.length > 0) {
      List<Clock> list = [];
      for (int i = 0; i < maps.length; i++) {
        list.add(Clock.fromJson(maps[i]));
      }
      // return formatListData(list);
      return list;
    }

    // var clockProvider = await _getClockProvider(db, userName);
    // if (clockProvider != null) {
    //   ///使用 compute 的 Isolate 优化 json decode
    //   var mapData =
    //       await compute(CodeUtils.decodeMapResult, clockProvider.data as String?);
    //   return Clock.fromJson(mapData);
    // }
    return null;
  }

  Future<Clock?> getDetail(String fDate) async {
    Database db = await getDataBase();
    // List<Map<String, dynamic>> maps = await db.query(name,
    //     where: "$columnFDate = ?", whereArgs: [fDate]);
    List<Map<String, dynamic>> maps = await db.rawQuery(
        'SELECT * FROM $name WHERE $columnFDate LIKE "$fDate%"',
        null
    );
    print('>>>>> getDetail: $maps');
    if (maps.length > 0) {
      return Clock.fromJson(maps.first);
    }
    return null;
  }
}
